<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <!-- 点击这个添加权限点添加的页面级别的权限点,传递的pid:'0',type:1 -->
          <el-button type="primary" size="small" @click="addPermission('0',1)">添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- 只有页面级别的节点,才展示添加按钮 -->
              <!-- 点击这个添加按钮是添加的按钮级别的权限点,传递的pid:本身的id type:2 -->
              <el-button v-if="scope.row.type===1" type="text" @click="addPermission(scope.row.id,2)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <!-- 有子部门的不可以显示删除按钮 -->
              <el-button v-if="scope.row&&!scope.row.children" type="text" @click="delPermission(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加权限点弹框 -->
        <el-dialog
          :title="isEdit?'编辑权限点':'新增权限点'"
          :visible="showDialog"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="btnCancel"
        >
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="addPermissionSubmit">{{ isEdit?'确认修改':'确认新增' }}</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'
import { transTree } from '@/utils/index'

export default {
  name: 'Permission',
  data() {
    // 定义校验权限名称 同级不能出现一样的
    const checkRoleName = (rule, value, callback) => {
      // 首先取到所有的同级节点
      let checkRoleNameList = this.originList.filter(item => item.pid === this.formData.pid).map(item => item.name)
      if (this.isEdit) {
        // 如果是编辑状态,先筛选出所有的兄弟元素,再将自己本身排除
        checkRoleNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      checkRoleNameList.includes(value) ? callback(new Error('部门名称' + value + '已存在')) : callback()
    }

    // 定义校验权限标识 他是唯一的
    const checkRoleCode = (rule, value, callback) => {
      let checkRoleCodeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        // 如果是编辑状态,将自己本身筛选出来
        checkRoleCodeList = this.originList.filter(item => item.id !== this.formData.id).map(item => item.code)
      }
      checkRoleCodeList.includes(value) ? callback(new Error('部门编码' + value + '已存在')) : callback()
    }
    return {
      permissionList: [], // 权限管理列表数据
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: checkRoleName, trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: checkRoleCode, trigger: 'blur' }]
      },
      isEdit: false, // 是否是编辑状态
      roleId: '', // 当前角色id
      originList: [] // 用于校验的数组
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 点击删除按钮
    async delPermission(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancael') this.$message('您已取消删除')
      const res = await delPermission(id)
      this.$message.success(res.message)
      this.getPermissionList()
    },
    // 点击编辑按钮
    async editPermission(id) {
      this.showDialog = true
      this.isEdit = true
      // 发送请求,回填数据
      this.roleId = id
      const res = await getPermissionDetail(this.roleId)
      this.formData = res.data
    },
    // 点击添加权限按钮或者编辑权限按钮的确认按钮
    addPermissionSubmit() {
      this.$refs.perForm.validate(async valid => {
        if (!valid) return
        // 判断是否是编辑状态
        if (this.isEdit) {
          // 如果是编辑状态,则调用编辑API
          await updatePermission(this.formData)
          // console.log(res)
        } else {
          // 如果不是新增权限
          await addPermission(this.formData)
          // console.log(res)
        }
        this.$message.success(this.isEdit ? '编辑权限点成功' : '新增权限点成功')
        this.showDialog = false
        this.getPermissionList()
      })
    },
    // 点击不同的添加权限点按钮,传递不同的参数
    addPermission(pid, type) {
      this.showDialog = true
      this.formData.pid = pid
      this.formData.type = type
      this.isEdit = false
    },
    // 点击取消 弹框关闭事件
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },
    // 获取所有的角色列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.originList = res.data.map(item => ({
        id: item.id,
        pid: item.pid,
        name: item.name.trim(), // 一定要消除前后方空格
        code: item.code
      }))
      this.permissionList = transTree(res.data, '0')
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body{
  padding: 30px 20px 0px 20px;
}

::v-deep .el-dialog__footer {
    padding: 0px 20px 20px;
}
</style>
